package com.example.quartz.app.service;

import com.example.quartz.app.dao.JobDao;
import com.example.quartz.app.entity.JobEntity;
import com.example.quartz.util.Utils;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class JobService {

    @Resource
    private JobDao jobDao;

    @Autowired
    private Scheduler scheduler;

    public String runNow(JobEntity jobEntity) throws SchedulerException {
        this.scheduler.triggerJob(new JobKey(jobEntity.getJobName(), jobEntity.getJobGroup()));
        return "success";
    }

    public String stopRun(JobEntity jobEntity) throws SchedulerException {
        this.scheduler.pauseJob(new JobKey(jobEntity.getJobName(), jobEntity.getJobGroup()));
        return "success";
    }

    public String stopAll(JobEntity jobEntity) throws SchedulerException {
        this.scheduler.pauseAll();
        return "success";
    }

    public String startRun(JobEntity jobEntity) throws SchedulerException {
        this.scheduler.resumeJob(new JobKey(jobEntity.getJobName(), jobEntity.getJobGroup()));
        return "success";
    }

    public String startAll(JobEntity jobEntity) throws SchedulerException {
        this.scheduler.resumeAll();
        return "success";
    }

    public String addJob(JobEntity jobEntity) throws SchedulerException {
        this.scheduler.scheduleJob(Utils.getJobDetail(jobEntity), Utils.getCronTrigger(jobEntity));
        jobDao.addJob(jobEntity);
        return "success";
    }

    public String deleteJob(JobEntity jobEntity) throws SchedulerException {
        this.stopRun(jobEntity);
        this.scheduler.deleteJob(new JobKey(jobEntity.getJobName(), jobEntity.getJobGroup()));
        JobEntity paramEntity = new JobEntity();
        paramEntity.setId(jobEntity.getId());
        paramEntity.setIsDelete(1);
        jobDao.updateJob(paramEntity);
        return "success";
    }

    public String updateJob(JobEntity jobEntity) throws SchedulerException {
        this.scheduler.rescheduleJob(new TriggerKey(jobEntity.getTriggerName(), jobEntity.getTriggerGroup()), Utils.getCronTrigger(jobEntity));
        jobDao.updateJob(jobEntity);
        return "success";
    }
}
